/**
 * 重复请求统一处理
 */
import axios from 'axios';

let pending = {};
const cancelToken = axios.CancelToken; // 初始化取消请求的构造函数

const removePending = (config, fn) => {
  // 通过 baseURL+url+method+repeatRequestKey 判定是否重复
  const flagUrl = config.baseURL + config.url + config.method + (config.repeatRequestKey || '');
  if (pending[flagUrl]) {
    pending[flagUrl](config);
    pending[flagUrl] = null;
  } else {
    if (fn) {
      pending[flagUrl] = fn;
    }
  }
};

export default instance => {
  // Add a request interceptor
  instance.interceptors.request.use(
    config => {
      config.cancelToken = new cancelToken(c => {
        removePending(config, c);
      });

      return config;
    },
    error => Promise.reject(error)
  );

  // Add a response interceptor
  instance.interceptors.response.use(
    response => {
      removePending(response.config);
      return response;
    },
    error => {
      // 自身错误不处理
      if (!axios.isCancel(error) && error.config) {
        removePending(error.config);
      }
      return Promise.reject(error);
    }
  );
};
